package fjut.acm.coding.utils;

import cn.hutool.core.util.IdUtil;
import fjut.acm.coding.entity.result.ResultCode;
import fjut.acm.coding.entity.result.ResultJson;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class PictureUtils {

    /**
     *
     * @param pic  图片文件
     * @param address  图片地址
     * @param type  图片类型（可以自定义）
     * @param prefix  映射的虚拟地址
     * @return
     * @throws IOException
     */
    public static String pictureAddress(final MultipartFile pic , String address , String type,String prefix) throws IOException {
        if (pic.getSize() == 0) {
            return null;
        }

        final byte[] bytes = pic.getBytes();
        String randFileName = type + IdUtil.simpleUUID();
        int len = Objects.requireNonNull(pic.getOriginalFilename()).split("\\.").length;
        String suffix = "";
        if (len > 0) {
            suffix = pic.getOriginalFilename().split("\\.")[len - 1];
        }
        final Path path = Paths.get(address + randFileName + "." + suffix);
        Files.write(path, bytes);
        return prefix + randFileName + "." + suffix;
    }
}
